package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/minimum-absolute-difference-in-bst/description/
 * <p>
 * 给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。
 * <p>
 * 差值是一个正数，其数值等于两值之差的绝对值。
 */
public class _28LetCode530_二叉搜索树的最小绝对差 {

    public int getMinimumDifference(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        int min = Integer.MAX_VALUE;
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                if (pre == null) {
                    pre = root;
                } else {
                    min = Math.min(min, root.val - pre.val);
                    pre = root;
                }
                root = root.right;
            }
        }
        return min;
    }

    public static void main(String[] args) {
        _28LetCode530_二叉搜索树的最小绝对差 sol = new _28LetCode530_二叉搜索树的最小绝对差();
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(6);
        System.out.println(sol.getMinimumDifference(root));

    }
}
